// 创建websocket 实例
import {
  ArrayQueue,
  ConstantBackoff,
  Websocket,
  WebsocketBuilder,
  WebsocketEvent,
} from 'websocket-ts'
import { MessageType } from '/@/utils/websocket/messageEnum'

import { WebSocketMessageContentType } from '/@/utils/websocket/messageEnum'



// const url: string = `${import.meta.env.VITE_WS_URL}${token ? `?token=${token}` : ''}`
const url_sub: string = `${import.meta.env.VITE_WS_LIVE_URL}`

console.log('url_sub:' + url_sub)
console.log('开始创建连接websocket.ts')


export class MyWebsocket {

  // 定义一个变量，存储当前连接状态
  public _isConnected: boolean = false
  // 当前的url
  public url: string = ''
  // 设置当前的token信息
  public _token: string = ''
  public _ws: Websocket | null = null

  public _roomId: number | undefined = 0

  private onConnectCallback?: () => void; // 保存回调函数
  private onCloseCallback?: () => void;
  private onMessageCallback?: (data: any) => void;

  // 初始化
  constructor(url: string|null, userId: number, roomId: number | undefined) {
    // 如果url不为空，则使用url
    if(url){
      this.url = url
    }else {
      // 如果url为空，则使用默认的url
      this.url = url_sub+'?token='+userId
    }
    this._roomId = roomId
    console.log('MyWebsocket 构造函数')
    console.log('url:' + url)
    console.log('roomId:' + roomId)
    // 如果是未连接的状态，则进行连接
    if (!this._isConnected) {
      // 进行初始化
      this.init()
    }
  }

  init() {
    this._ws = new WebsocketBuilder(this.url)
      .withBuffer(new ArrayQueue())           // buffer messages when disconnected
      .withBackoff(new ConstantBackoff(1000)) // retry every 1s
      .build()
    console.log('MyWebsocket 初始化成功')
    // // 监听连接状态
    this._ws.addEventListener(WebsocketEvent.open, () => {
      console.log('成功连接，现在开始发送加入房间的消息!')
      this.onConnectCallback?.(); // 触发回调函数
    })

    this._ws.addEventListener(WebsocketEvent.close, () => {
      console.log('连接断开')
      this.onCloseCallback?.(); // 触发回调函数
    })

    this._ws.addEventListener(WebsocketEvent.message, (i: Websocket, ev: MessageEvent) => {
      this.onMessageCallback?.(ev.data)
    })
  }

  // 发送消息
  send(data: WebSocketMessageContentType) {
    // 发送消息
    this._ws?.send(JSON.stringify(data))
  }
  setOnConnect(callback: () => void) {
    // 保存回调函数
    this.onConnectCallback = callback
  }

  setOnClose(callback: () => void) {
    // 保存回调函数
    this.onCloseCallback = callback
  }

  setOnMessage(callback: (data: any) => void) {
    // 保存回调函数
    this.onMessageCallback = callback
  }

}


// 创建websocket 连接，使用缓冲区。并且设置了1秒钟的重新连接机制
// export const ws = new WebsocketBuilder(url_sub)
//   .withBuffer(new ArrayQueue())           // buffer messages when disconnected
//   .withBackoff(new ConstantBackoff(1000)) // retry every 1s
//   .build()

// Function to output & echo received messages
// const echoOnMessage = (i: Websocket, ev: MessageEvent) => {
//   console.log(`received message: ${ev.data}`);
// };
//
// // 添加监听器
// ws.addEventListener(WebsocketEvent.open, () => {
//   console.log("connected!");
//   ws.send("hello world");
// });
// ws.addEventListener(WebsocketEvent.close, () => {
//   console.log("disconnected!");
// });
//
// // 当接受到消息时，就回显
// ws.addEventListener(WebsocketEvent.message, echoOnMessage);


